package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.OrgConsoleService;
import com.ibeetl.admin.console.service.RoleConsoleService;
import com.ibeetl.admin.console.service.UserConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.*;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.TodoService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.query.TestQuery;
import com.ibeetl.cms.util.RoleConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 待办任务接口
 */
@Controller
public class TodoController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "cms/todo";

    @Autowired
    CorePlatformService platformService;

    @Autowired
    private TodoService testService;

    @Autowired
    UserConsoleService userConsoleService;

    @Autowired
    RoleConsoleService roleConsoleService;

    @Autowired
    OrgConsoleService orgConsoleService;

    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("cms.todo.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("cms/todo/index.html");
        view.addObject("search", TestQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("cms.todo.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("cms/todo/edit.html");
        Test test = testService.queryById(id);
        view.addObject("test", test);

        List<Map<String, String>> keys = new ArrayList<Map<String, String>>();
        Map<String, String> m = new HashMap<>();
        m.put("id", "1");
        m.put("name", "敬仰");
        keys.add(m);
        Map<String, String> m2 = new HashMap<>();
        m2.put("id", "2");
        m2.put("name", "深陷");
        keys.add(m2);
        view.addObject("keys", keys);

        return view;
    }

    @GetMapping(MODEL + "/todo.do")
    @ResponseBody
    public ModelAndView todo() {
        ModelAndView view = new ModelAndView("cms/todo/todo.html");
        return view;
    }

    @GetMapping(MODEL + "/todo.json")
    @ResponseBody
    public JsonResult<List<Todo>> todolist() {

        CoreUser user = platformService.getCurrentUser();
        CoreRole role = platformService.getRole();

        List<Todo> result = new ArrayList<>(16);
        if (role.getId() == RoleConstant.PERSON) {
            TestQuery query = new TestQuery();
            query.setUserId(user.getId());
            query.setBusinessStateCode("0");
            result = testService.getTodoList(query);
        }
        /*
        if role is company
         */
        else if (role.getId() == RoleConstant.COMPANY) {
            TestQuery query = new TestQuery();
            query.setUserId(user.getId());
            query.setBusinessStateCode("1");
            result = testService.getCompanyTodoList(query);
        }
        /*
        if role is check
         */
        else if (role.getId() == RoleConstant.FIRSTCHECK) {
            TestQuery query = new TestQuery();
            query.setBusinessStateCode("2");
            result = testService.getCheckTodoList(query);
        } else if (role.getId() == RoleConstant.FINALCHECK) {
            TestQuery query = new TestQuery();
            query.setBusinessStateCode("3");
            result = testService.getCheckTodoList(query);
        }
        return JsonResult.success(result);
    }

    @GetMapping(MODEL + "/add.do")
    @Function("cms.todo.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("cms/todo/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("cms.todo.query")
    @ResponseBody
    public JsonResult<PageQuery> list(TestQuery condtion) {
        PageQuery page = condtion.getPageQuery();
        testService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("cms.todo.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class) Test test) {
        CoreUser user = new CoreUser();
        user.setName("my name");
        user.setCode(test.getName());
        user.setPassword(test.getPhone());
        user.setState("1");
        user.setOrgId((long) 1);
        if (!platformService.isAllowUserName(user.getCode())) {
            return JsonResult.failMessage("不允许的注册名字 " + user.getCode());
        }
        user.setCreateTime(new Date());
        userConsoleService.saveUser(user);

        CoreUserRole userRole = new CoreUserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId((long) 176);
        userRole.setOrgId(user.getOrgId());
        userRole.setCreateTime(new Date());
        this.userConsoleService.saveUserRole(userRole);
        this.platformService.clearFunctionCache();
        return JsonResult.success(user.getId());
    }

    @PostMapping(MODEL + "/update.json")
    @Function("cms.todo.update")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class) Test test) {
        boolean success = testService.updateTemplate(test);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


    @GetMapping(MODEL + "/view.json")
    @Function("cms.todo.query")
    @ResponseBody
    public JsonResult<Test> queryInfo(Integer id) {
        Test test = testService.queryById(id);
        return JsonResult.success(test);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("cms.todo.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        testService.batchDelTest(idList);
        return new JsonResult().success();
    }


    @PostMapping(MODEL + "/excel/export.json")
    @Function("cms.todo.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response, TestQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此testService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate = "excelTemplatescms/todo/你的excel模板文件名字.xls";
        PageQuery<Test> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<Test> list = testService.queryByCondition(page).getList();
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if (is == null) {
                throw new PlatformException("模板资源不存在：" + excelTemplate);
            }
            FileItem item = fileService.createFileTemp("Test_" + DateUtil.now("yyyyMMddHHmmss") + ".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }

    }

    @PostMapping(MODEL + "/excel/import.do")
    @Function("cms.todo.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }


}
